package com.shteo.crmd.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Akuma on 16/2/3.
 */
@Component
public class BaseController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;


    /**
     * 处理请求日期参数
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true允许空值
    }

    /**
     * 返回request
     * @return HttpServletRequest
     */
    public HttpServletRequest getRequest(){
        return request;
    }

    /**
     * 返回response
     * @return
     */
    public HttpServletResponse getResponse() {
        return response;
    }

    /**
     * 设置HttpServletRequest属性
     * @param key
     * @param value
     */
    public void setRequestAttr(String key,Object value){
        getRequest().setAttribute(key,value);
    }

    /**
     * 获取HttpServletRequest属性值
     * @param key
     * @return
     */
    public Object getRequestAttr(String key){
        return getRequest().getAttribute(key);
    }

    /**
     * 返回session
     * @return HttpSession
     */
    public HttpSession getHSession(){
        return request.getSession();
    }

    /**
     * 设置session属性值
     * @param key
     * @param obj
     */
    public void setHSessionAttr(String key,Object obj){
        getHSession().setAttribute(key,obj);
    }

    /**
     * 获取session属性值
     * @param key
     */
    public Object getHSessionAttr(String key){
        return getHSession().getAttribute(key);
    }

}
